﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Text;
using System.Threading.Tasks;

using Microsoft.SharePoint.Client;

using System.Web.Mvc;

namespace SharepointPlugin.Controllers
{
    public class SharepointController : Controller
    {
        public ActionResult ArticleList(string pageListName)
        {
            string viewName = "Articles-Title";
            ViewBag.ArticleUrlTemplate = "/articles/{0}";
            return PartialView(viewName, BizRules.GetArticles((Models.SpointConnectionInfo)HttpContext.Application["SharepointId"], pageListName));
        }

        public ActionResult Article(int artId, string pageListName)
        {
            string viewName = "Article-TitleBody";
            return PartialView(viewName, BizRules.GetArticle((Models.SpointConnectionInfo)HttpContext.Application["SharepointId"], artId, pageListName));
        }

        public ActionResult Documents(string fileName)
        {
            return new FileStreamResult(BizRules.getDocumentStream((Models.SpointConnectionInfo)HttpContext.Application["SharepointId"], "Shared Documents/" + fileName), "image/jpeg");
        }

        public ActionResult ListItems(string listName, string viewName)
        {
            if(string.IsNullOrWhiteSpace(viewName))
                viewName = "ListItems-Title";
            ViewBag.UrlTemplate = "/spd/"+listName+"/{0}";
            return PartialView(viewName, BizRules.GetListItems((Models.SpointConnectionInfo)HttpContext.Application["SharepointId"], listName));
        }

        public ActionResult ListItem(string listName, int id)
        {
            Models.SpointItem item = BizRules.GetListItem((Models.SpointConnectionInfo)HttpContext.Application["SharepointId"], listName, id);
            string viewName = viewNameFactoryMethod("ListItem-TitleBody", item, listName);
            return View(viewName, item);
        }

        protected virtual string viewNameFactoryMethod(string defaultView, Models.SpointItem item, string listName)
        {
            if (item.BaseTemplate == (int)ListTemplateType.Tasks || 
                item.BaseTemplate == (int)ListTemplateType.TasksWithTimelineAndHierarchy)
                return "ListItem-TaskType";

            //This does not belong here because registered plugins is a custom list type for the main site, but for now this is what we can do to get by.
            if (item.BaseTemplate == (int)ListTemplateType.GenericList && string.Compare(listName, "Registered Plugins", true) ==0)
                return "RegisteredPlugins-FullPageInfo";
            return defaultView;
        }
    }
}
